<?php

namespace App\Http\Controllers;

use App\Http\Requests\RoleRequest;
use App\Models\Role;
use App\Transformers\RoleTransformer;
use Illuminate\Http\Request;
use Dingo\Api\Transformer\Factory;
use Illuminate\Validation\Rule;

class RoleController extends Controller
{
    /**
     * @api {get} /api/roles?include=children 角色列表
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *                       "id": 1,
     *                       "name": "超级管理员",
     *                       "parent_id": null,
     *                       "is_role": false,
     *                       "created_at": "2018-12-13 15:48:41",
     *                       "updated_at": "2018-12-13 15:48:41"
     *                   },
     *                   {
     *                       "id": 2,
     *                       "name": "运维",
     *                       "parent_id": null,
     *                       "is_role": false,
     *                       "created_at": "2018-12-13 15:48:41",
     *                       "updated_at": "2018-12-13 15:48:41"
     *                   },
     *                   {
     *                       "id": 5,
     *                       "name": "root",
     *                       "parent_id": null,
     *                       "is_role": false,
     *                       "created_at": "2018-12-13 16:01:53",
     *                       "updated_at": "2018-12-13 16:01:53"
     *               }
     *           ]
     *       }
     */
    public function index(Request $request, Factory $transformerFactory){
        if ($request->include == 'children') {
            $categories = Role::defaultOrder()->get()->toTree();
            // 关闭 Dingo 的预加载
            $transformerFactory->disableEagerLoading();
        } else {
            $categories = Role::whereIsRoot()->defaultOrder()->get();
        }

        return $this->response->collection($categories, new RoleTransformer());
    }

    /**
     * @api {post} /api/roles 角色添加（添加部门，添加分支，添加岗位）
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} name  名称（必传参数）
     * @apiParam {int} parent_id  父节点id
     * @apiParam {int} is_role  是否是角色
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 201 OK
     */
    public function store(RoleRequest $request, Role $role){
        $role->fill($request->all());
        $role->save();
        return $this->response->created();
    }

    /**
     * @api {get} /api/roles/:rele 角色展示
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} role 角色id(url中传入，必传参数)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "id": 1,
     *           "name": "超级管理员",
     *           "parent_id": null,
     *           "created_at": "2018-12-13 15:48:41",
     *           "updated_at": "2018-12-13 15:48:41"
     *       }
     */
    public function show(Role $role){
        return $this->response->item($role, new RoleTransformer());
    }

    /**
     * @api {delete} /api/roles/:rele 角色删除
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} role 角色id(url中传入，必传参数)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     */
    public function destroy(Role $role){
        if($role->children->toArray()){
            return response()->json(['error' => '请先删除后代节点'], 422);
        }
        if($role->users()->get()->toArray()){
            return response()->json(['error' => '角色下有用户'], 422);
        }
        $role->delete();
        return $this->response->noContent();
    }

    /**
     * @api {patch} /api/roles/:rele 角色修改
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} name 角色名
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *             "message": "修改成功"
     *       }
     */
    public function update(RoleRequest $request, Role $role){

        $role->update($request->only('name'));
        return response()->json(['message' => '修改成功']);
    }

    /**
     * @api {get} /api/roles/:rele/children 获取角色后代
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} role 角色id(url中传入，必传参数)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     *       {
     *           "id": 3,
     *           "name": "运维儿子",
     *           "guard_name": "api",
     *           "_lft": 4,
     *           "_rgt": 7,
     *           "parent_id": 2,
     *           "created_at": "2018-12-14 10:25:46",
     *           "updated_at": "2018-12-14 10:25:46",
     *           "deleted_at": null,
     *           "is_role": false,
     *           "children": [
     *               {
     *                   "id": 4,
     *                   "name": "运维角色",
     *                   "guard_name": "api",
     *                   "_lft": 5,
     *                   "_rgt": 6,
     *                   "parent_id": 3,
     *                   "created_at": "2018-12-14 10:26:21",
     *                   "updated_at": "2018-12-14 10:26:21",
     *                   "deleted_at": null,
     *                   "is_role": true,
     *                   "children": []
     *               }
     *           ]
     *       }
     *
     */
    public function children(Role $role){
        $res = $role->children;
        return response()->json($res);
    }

    /**
     * @api {get} /api/roles/:role/permissions 角色对应权限
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} role 角色id(url中传入，必传参数)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       [
     *           {
     *               "id": 1,
     *               "name": null,
     *               "alias": "组织架构api",
     *               "guard_name": "api",
     *               "_lft": 1,
     *               "_rgt": 10,
     *               "parent_id": null,
     *               "created_at": "2018-12-17 19:29:18",
     *               "updated_at": "2018-12-18 10:09:07",
     *               "deleted_at": null,
     *               "pivot": {
     *                   "role_id": 1,
     *                   "permission_id": 1
     *               },
     *           }
     *       ]
     *
     */
    public function rolePermissions(Role $role){
        if($role->is_role == true){
            $permissions = $role->permissions()->get()->toArray();
        }else{
            $permissions = [];
        }

        return response()->json($permissions);
    }
    /**
     * @api {patch} /api/roles/:role/permissions 角色权限修改
     * @apiGroup Role
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} role 角色id(url中传入，必传参数)
     * @apiParam {array} ids 权限id(
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "message": "修改成功"
     *       }
     *
     */
    public function rolePermissionsUpdate(Role $role, Request $request){
        $validatedData = $request->validate([
            'ids' => 'array',
            'ids.*' => 'exists:permissions,id',
        ],[],[
            'ids'=>'权限',
            'ids.*'=>'权限'
        ]);
        $role->syncPermissions($validatedData['ids']);

        return response()->json(['message'=>'修改成功']);
    }
}
